<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-input
            v-model="departname"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="departments2"
            :props="defaultProps"
            accordion
            :expand-on-click-node="true"
            :filter-node-method="filterNode"
            ref="tree"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="19" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="员工名称" prop="username">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入员工名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="telphone">
            <el-input
              v-model="queryParams.telphone"
              placeholder="请输入手机号码"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
<!--          <el-form-item label="部门" prop="deparid">-->
<!--            <el-select v-model="queryParams.deparid" placeholder="请选择部门" filterable clearable size="small">-->
<!--              <el-option-->
<!--                v-for="item in departments"-->
<!--                :key="item.guid"-->
<!--                :label="item.name"-->
<!--                :value="item.guid"-->
<!--                @change="handleQuery"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:employee:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:employee:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:employee:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:employee:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="employeeList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="员工名称" align="center" prop="username" />
          <el-table-column label="性别" align="center" prop="sex" :formatter="packSex" />
          <el-table-column label="手机号码" align="center" prop="telphone" />
          <el-table-column label="部门名称" align="center" prop="departname" />
          <el-table-column label="员工NO(金蝶)" align="center" prop="ownerKdn" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:employee:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:employee:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改员工管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="员工" prop="username">
          <el-select v-model="form.username" placeholder="请选择员工" filterable clearable size="small">
            <el-option
              v-for="item in users"
              :key="item.guid"
              :label="item.realname"
              :value="item.realname"
              @click.native="getCurrUser($event, item)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <template>
            <el-radio v-model="sex" label="1">男</el-radio>
            <el-radio v-model="sex" label="0">女</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="手机号码" prop="telphone">
          <el-input v-model="form.telphone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="部门" prop="deparid">
          <el-select v-model="form.deparid" placeholder="请选择部门" filterable clearable size="small">
            <el-option
              v-for="item in departments"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { listEmployee, getEmployee, delEmployee, addEmployee, updateEmployee, exportEmployee, listDept } from "@/api/system/employee";
  import { listOldUser } from "@/api/system/user";

  export default {
    name: "Employee",
    components: {
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 员工管理表格数据
        employeeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userid: null,
          username: null,
          deparid: null,
          ownerKdn: null
        },
        // 表单参数
        form: {
          sex: '1'
        },
        // 表单校验
        rules: {
          username: [
            { required: true, message: '请选择员工', trigger: 'blur' }
          ],
          telphone: [
            { required: true, message: '请填写手机号', trigger: 'blur' },
          ],
          deparid: [
            { required: true, message: '请选择部门', trigger: 'blur' },
          ]
        },
        departments: [],
        departments2: [],
        depart: '',
        users: [],
        employee: '',
        sex: '1',
        defaultProps: {
          children: "children",
          label: "name"
        },
        // 部门名称
        departname: undefined,
      };
    },
    watch: {
      // 根据名称筛选部门树
      departname(val) {
        this.$refs.tree.filter(val);
      }
    },
    created() {
      this.getList();
      this.getDeparts();
      this.getUsers();
    },
    methods: {
      packSex(sex) {
        return sex == 0 ? '女' : '男';
      },
      getCurrUser(e, item) {
        this.$set(this.form, 'userid', item.guid);
        this.$set(this.form, 'telphone', item.telphone);
        if (item.sex !== null) {
          this.sex = `${item.sex}`;
          this.form.sex = item.sex;
        }
      },
      /** 查询员工管理列表 */
      getList() {
        this.loading = true;
        listEmployee(this.queryParams).then(response => {
          this.employeeList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      getDeparts() {
        listDept().then(response => {
          this.departments = response.data;
          this.packDeparts();
        });
      },
      packDeparts: function() {
        const depts = [];
        const depts2 = [];
        const depts3 = [];
        this.departments.filter(item => {
          //一级部门
          if (item.code.length == 3) {
            depts.push(item);
          }
          //二级部门
          if (item.code.length == 6) {
            depts2.push(item);
          }
          //三级部门
          if (item.code.length == 9) {
            depts3.push(item);
          }
        });
        depts2.filter(item => {
            depts.map(d => {
              if (d.code == item.code.substr(0, 3)) {
                if (d.children) {
                  d.children.push(item);
                  return d;
                } else {
                  d.children = [item];
                  return d;
                }
              }
            })
        })
        depts3.filter(item => {
          depts.map(d => {
            if (d.children) {
              return d.children.map(dd => {
                if (dd.code == item.code.substr(0, 6)) {
                  console.log('dd.code:', dd.code)
                  if (dd.children) {
                    dd.children.push(item);
                    return dd;
                  } else {
                    dd.children = [item];
                    return dd;
                  }
                }
              })
            }
          })
        })
        this.departments2 = depts;
      },
      getUsers() {
        listOldUser().then(response => {
          this.users = response.data;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          userid: null,
          username: null,
          deparid: null,
          departname: null,
          ownerKdn: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.deparid = data.guid;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加员工管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getEmployee(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改员工管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateEmployee(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addEmployee(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除该数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delEmployee(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有员工管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportEmployee(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      }
    }
  };
</script>
